var express = require('express');
const mongoose = require('mongoose')
var router = express.Router();
var DateModule = require('../../databases/date')
var axios = require('axios')
/* GET users listing. */
router.get('/', function (req, res, next) {
  res.send('respond with a resource');
});

//获取收货地址列表
router.get('/getaddress', async function (req, res, next) {
  try {
    const { userId } = req.query
    // 直接用 userId 作为查询条件
    const data = await DateModule.address.find(userId ? { userId } : {})
    res.json({
      code: 200,
      data
    })
  } catch (err) {
    res.json({
      code: 500,
      message: '数据库查询失败',
      error: err.message
    })
  }
})


//获取订单列表
router.get('/getdingdan', async function (req, res, next) {
  try {
    const { userId } = req.query
    let query = {}
    if (userId) {
      query.userId = new mongoose.Types.ObjectId(userId)
    }
    const data = await DateModule.dingdan.find(query).populate('shopsId', '_id name')
    res.json({
      code: 200,
      data
    })
  } catch (err) {
    res.json({
      code: 500,
      message: '数据库查询失败',
      error: err.message
    })
  }
})
// 设置默认地址
router.post('/setDefaultAddress', async function (req, res) {
  try {
    const { userId, addressId } = req.body
    if (!userId || !addressId) {
      return res.json({ code: 400, message: '参数缺失' })
    }
    // 先将该用户所有地址的 isDefault 设为 false
    await DateModule.address.updateMany({ userId: new mongoose.Types.ObjectId(userId) }, { isDefault: false })
    // 再将选中的地址 isDefault 设为 true
    await DateModule.address.findByIdAndUpdate(addressId, { isDefault: true })
    res.json({ code: 200, message: '设置成功' })
  } catch (err) {
    res.json({ code: 500, message: '设置失败', error: err.message })
  }
})
//修改收货地址
router.post('/updateAddress', async function (req, res) {
  try {
    const { userId, address } = req.body
    if (!userId || !address) {
      return res.json({ code: 400, message: '参数缺失' })
    }
    await DateModule.address.findByIdAndUpdate(address._id, address)
    res.json({ code: 200, message: '修改成功' })
  } catch (err) {
    res.json({ code: 500, message: '修改失败', error: err.message })
  }
})
// 添加收货地址
router.post('/addAddress', async function (req, res) {

  // {
  //   userId: '68653b928e724b9927f7d3a5',
  //   address: '文档发',
  //   isDefault: true,
  //   name: '地方v从吧',
  //   phone: '15031042799',
  //   areaCode: '110101',
  //   area: '北京市北京市东城区'
  // }
  try {
    const { userId, address, isDefault, name, phone, areaCode, area } = req.body
    if (!userId || !name || !phone || !areaCode || !address) {
      return res.json({ code: 400, message: '参数缺失' })
    }
    // 如果设为默认，先将该用户所有地址的 isDefault 设为 false
    if (isDefault) {
      await DateModule.address.updateMany({ userId: new mongoose.Types.ObjectId(userId) }, { isDefault: false })
    }
    // console.log(req.body);
    // 新增地址
    const newAddr = await DateModule.address.create({
      userId: new mongoose.Types.ObjectId(userId),
      name,
      phone,
      areaCode,
      area,
      address,
      isDefault: !!isDefault
    })
    res.json({ code: 200, message: '添加成功', data: newAddr })
  } catch (err) {
    res.json({ code: 500, message: '添加失败', error: err.message })
  }
})

// 删除收货地址
router.post('/deleteAddress', async function (req, res) {
  try {
    const { addressId } = req.body
    if (!addressId) {
      return res.json({ code: 400, message: '参数缺失' })
    }
    await DateModule.address.findByIdAndDelete(addressId)
    res.json({ code: 200, message: '删除成功' })
  } catch (err) {
    res.json({ code: 500, message: '删除失败', error: err.message })
  }
})

//获取用户列表
router.get('/getuser', function (req, res, next) {
  res.json(
    {
      code: 200,
      data: DateModule.user.find()
    }
  )
});
//获取用户地理位置
router.get('/amap',function (req, res, next) {
  const { longitude, latitude } = req.query
  console.log('经度:', longitude, '纬度:', latitude);
  
  axios.get(`https://restapi.amap.com/v3/geocode/regeo?location=${longitude},${latitude}&key=a11f0cfcc581b99eb81e1a93a1ed4957&radius=1000&extensions=base`).then((res) => {
    if (res.status === '1') {
      // 成功获取地址信息
      const streetNumber = res.regeocode.addressComponent.streetNumber
      const street = streetNumber.street
      const number = streetNumber.number
      const adcode = res.regeocode.addressComponent.adcode
      // 更新地址信息
      let addressInfo= {
        areaCode: adcode,
        addressDetail: `街道：${street}, 门牌：${number}`,
      }
      res.json({
        code: 200,
        data: addressInfo
      })
    }
  }).catch((err) => {
    console.error('请求错误:', err, 224)

  })
})
module.exports = router;